package com.meixiang.activity.homes.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.activity.account.CouponActivity;
import com.meixiang.activity.account.manager.AddressActivity;
import com.meixiang.activity.account.myShopper.MyAllOrderActivity;
import com.meixiang.dialog.DeliveryMethodDialogFragment;
import com.meixiang.dialog.LoadingDialog;
import com.meixiang.entity.OrderResult;
import com.meixiang.entity.account.AddressListEntity;
import com.meixiang.entity.shopping.CartGoodsEntity;
import com.meixiang.entity.shopping.GoodsOrderRequest;
import com.meixiang.entity.shopping.TransportEntity;
import com.meixiang.entity.shopping.result.BalanceAccountResult;
import com.meixiang.entity.shopping.result.CalculatePriceResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.OrderGoodsView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 确认商品订单
 *
 * @author LZRUI
 */
public class VerifyGoodsOrderActivity extends BaseActivity implements DeliveryMethodDialogFragment.TransportChangeListener {

    private static final String TAG = "VerifyGoodsOrderActivity";

    public static final String ORDER_DATA = "orderData";
    public static final String ADDRESS = "address";
    public static final String CP_ID = "cpId";
    public static final String CP_PRICE = "cpPrice";
    private static final int SELECT_ADDRESS_RQ_CODE = 0x01;  // 选择地址RequestCode
    private static final int ADD_ADDRESS_RQ_CODE = 0x02; // 添加地址RequestCode
    private static final int COUPON_RQ_CODE = 0x03; // 选择优惠卷RequestCode

    @Bind(R.id.tv_total_price)
    TextView tvTotalPrice; // 总价格
    @Bind(R.id.tv_goods_total_num)
    TextView tvGoodsTotalNum; // 商品数量
    @Bind(R.id.tv_integral)
    TextView tvIntegral; // 美积分
    @Bind(R.id.cb_integral)
    TextView cbIntegral;
    @Bind(R.id.tv_store_name)
    TextView tvStoreName; // 商店名称
    @Bind(R.id.order_view)
    OrderGoodsView orderView; // 商品列表
    @Bind(R.id.tv_delivery_method)
    TextView tvDeliveryMethod; // 配送方式
    @Bind(R.id.tv_coupon)
    TextView tvCoupon; // 优惠券
    @Bind(R.id.edt_message)
    ClearEditText edtMessage; // 留言
    @Bind(R.id.ll_has_no_address)
    LinearLayout llHasNoAddress; // 未添加地址
    @Bind(R.id.ll_address)
    LinearLayout llAddress; // 已经有地址
    @Bind(R.id.tv_user_name)
    TextView tvUserName; // 用户姓名
    @Bind(R.id.tv_phone_num)
    TextView tvPhoneNum; // 电话号码
    @Bind(R.id.tv_address)
    TextView tvAddress; // 地址
    @Bind(R.id.ll_integral)
    LinearLayout llIntegral; // 积分

    private BalanceAccountResult balanceAccountResult; // 提交订单接口的返回值
    private LoadingDialog loadingDialog;
    // 临时变量
    private List<TransportEntity> mTransportList;
    private String mUsePoint = "N";
    private String mAddressId;
    private String mCouponId;
    private TransportEntity mSelectTransport;
    private GoodsOrderRequest request = new GoodsOrderRequest();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_verify_goods_order);
        ButterKnife.bind(this);
        if (getIntent() != null) {
            balanceAccountResult = getIntent().getParcelableExtra(ORDER_DATA);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        HttpUtils.tagCancelRequest(TAG);
    }

    @Override
    protected void initTitle() {
        setTitle("确认订单");
    }

    @Override
    protected void initView() {
        loadingDialog = new LoadingDialog(this);
        MXApplication.mApp.AddActivity(this);
    }

    @Override
    protected void setData() {
        if (balanceAccountResult == null) return;
        String address = balanceAccountResult.getAreaInfo() + balanceAccountResult.getAddress();
        hasNoAddress(address, balanceAccountResult.getTrueName(), balanceAccountResult.getMobPhone());
        tvCoupon.setText(String.format(getString(R.string.coupon_str), balanceAccountResult.getCouponPrice()));
        tvStoreName.setText(balanceAccountResult.getStoreName());
        tvTotalPrice.setText(String.format(getString(R.string.price_str), balanceAccountResult.getTotalPrice()));
        tvGoodsTotalNum.setText(String.format(getString(R.string.total_goods_num), balanceAccountResult.getGoodsTotalCount()));
        orderView.setGoodsList(balanceAccountResult.getCartGoodsList());
        mTransportList = balanceAccountResult.getTransport();
        setTransport(0); // 第一种快递方式为默认方式
        mAddressId = balanceAccountResult.getAddressId();
        mCouponId = balanceAccountResult.getCouponId();
        showIntegral(balanceAccountResult.getIsPayPoint(), balanceAccountResult.getPointText());
    }

    /**
     * 显示积分布局
     *
     * @param isPayPoint 可用积分
     * @param pointText  积分显示文本
     */
    private void showIntegral(String isPayPoint, String pointText) {
        if (TextUtils.isEmpty(isPayPoint) || isPayPoint.equals("0")) {
            llIntegral.setVisibility(View.GONE);
        } else {
            llIntegral.setVisibility(View.VISIBLE);
            tvIntegral.setText(pointText);
        }
    }

    @OnClick({R.id.tv_add_address, R.id.ll_address, R.id.ll_integral, R.id.tv_submit_order, R.id.ll_coupon, R.id.ll_delivery_method})
    @Override
    public void onClick(View v) {
        if (Tool.isFastDoubleClick()) return;
        switch (v.getId()) {
            // 添加地址
            case R.id.tv_add_address:
                Intent addIntent = new Intent(this, AddressActivity.class);
                addIntent.putExtra("status", "2");
                addIntent.putExtra("fromOrder", true);
                startActivityForResult(addIntent, ADD_ADDRESS_RQ_CODE);
                break;
            // 选择地址
            case R.id.ll_address:
                startActivityForResult(new Intent(this, SelectGoodsReceiptAddressActivity.class), SELECT_ADDRESS_RQ_CODE);
                break;
            // 是否使用积分
            case R.id.ll_integral:
                boolean check = cbIntegral.isEnabled();
                cbIntegral.setEnabled(!check);
                if (!check) {
                    mUsePoint = "Y";
                } else {
                    mUsePoint = "N";
                }
                if (mSelectTransport != null) {
                    updatePrice(mCouponId, mUsePoint, mAddressId, mSelectTransport.getTransportId());
                }
                break;
            // 提交订单
            case R.id.tv_submit_order:

                submitOrder();

                break;
            // 优惠劵
            case R.id.ll_coupon:
                Intent couponIntent = new Intent(VerifyGoodsOrderActivity.this, CouponActivity.class);
                couponIntent.putExtra(CouponActivity.FROMCODE, CouponActivity.CODE);
                couponIntent.putExtra(CouponActivity.STOREID, balanceAccountResult.getStoreId());
                couponIntent.putExtra(CouponActivity.GOODSPRICE, balanceAccountResult.getGoodsPrice());
                startActivityForResult(couponIntent, COUPON_RQ_CODE);
                break;
            // 配送方式
            case R.id.ll_delivery_method:
                if (mTransportList != null && mTransportList.size() > 0) {
                    DeliveryMethodDialogFragment
                            .newInstance((ArrayList<TransportEntity>) mTransportList)
                            .setTransportChangeListener(VerifyGoodsOrderActivity.this)
                            .show(getSupportFragmentManager(), DeliveryMethodDialogFragment.TAG);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == RESULT_OK) {
            if (requestCode == SELECT_ADDRESS_RQ_CODE || requestCode == ADD_ADDRESS_RQ_CODE) {
                AddressListEntity entity = data.getParcelableExtra(ADDRESS);
                if (entity != null) {
                    hasNoAddress(entity.getAreaInfo() + entity.getAddress(), entity.getTrueName(), entity.getMobPhone());
                    mAddressId = entity.getAddressId();
                }
            } else {
                mCouponId = data.getStringExtra(CP_ID);
            }
            if (mSelectTransport != null) {
                updatePrice(mCouponId, mUsePoint, mAddressId, mSelectTransport.getTransportId());
            }
        }

    }

    @Override
    public void onTransportChange(int position) {
        setTransport(position);
        if (mSelectTransport != null) {
            updatePrice(mCouponId, mUsePoint, mAddressId, mSelectTransport.getTransportId());
        }
    }

    /**
     * 根据地址情况显示不同布局
     */
    private void hasNoAddress(String address, String personName, String phoneNum) {
        if (TextUtils.isEmpty(address)) {
            llHasNoAddress.setVisibility(View.VISIBLE);
            llAddress.setVisibility(View.GONE);
        } else {
            llHasNoAddress.setVisibility(View.GONE);
            llAddress.setVisibility(View.VISIBLE);
            tvUserName.setText(String.format(getString(R.string.goods_send_to), personName));
            tvPhoneNum.setText(phoneNum);
            tvAddress.setText(address);
        }
    }

    /**
     * 设置邮费
     */
    private void setTransport(int position) {
        if (mTransportList != null && mTransportList.size() > 0) {
            mSelectTransport = mTransportList.get(position);
            if (mSelectTransport.getTransportPrice().trim().equals("0") || mSelectTransport.getTransportPrice().trim().equals("0.00")) {
                tvDeliveryMethod.setText(mSelectTransport.getTransportName());
            } else {
                tvDeliveryMethod.setText(String.format(getString(R.string.goods_transport), mSelectTransport.getTransportName(), mSelectTransport.getTransportPrice()));
            }
        }
    }

    /**
     * 修改地址、优惠卷、快递方式、使用积分更新总价格
     *
     * @param usePoint "Y"/"N"
     */
    private void updatePrice(String couponId, final String usePoint, String addressId, final String transportId) {
        HttpParams params = new HttpParams();
        params.put("couponId", couponId);
        params.put("cartIds", createCartIdsStr());
        params.put("usePoint", usePoint);
        params.put("addressId", addressId);
        params.put("transportId", transportId);

        Log.i("lzrtest", "CALCULATE_PRICE ==  " + params.toString());

        HttpUtils.post(Config.CALCULATE_PRICE, TAG, params, new HttpCallBack(VerifyGoodsOrderActivity.this) {

            @Override
            public void onBefore(BaseRequest request) {
                if (loadingDialog == null || loadingDialog.isShowing()) return;
                loadingDialog.show();
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                if (loadingDialog == null) return;
                loadingDialog.dismiss();
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                CalculatePriceResult selectCouponResult = AbJsonUtil.fromJson(result.toString(), CalculatePriceResult.class);
                tvCoupon.setText(String.format(getString(R.string.coupon_str), selectCouponResult.getCouponPrice()));
                tvTotalPrice.setText(String.format(getString(R.string.price_str), selectCouponResult.getTotalPrice()));
                mTransportList = selectCouponResult.getTransport();
                showIntegral(selectCouponResult.getIsPayPoint(), selectCouponResult.getPointText());
                setTransport(0); // 第一种快递方式为默认方式
                if (usePoint.equals("Y")) {
                    // 设置submitOrder接口请求参数
                    request.setPointBalance(selectCouponResult.getPointBalance());
                    request.setIsPayPoint(selectCouponResult.getIsPayPoint());
                }
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(VerifyGoodsOrderActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 提交订单
     */
    private void submitOrder() {

        if (TextUtils.isEmpty(mAddressId)) {
            Toast.makeText(this, "请添加收货地址", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.i("lzrtest", "提交订单：  " + new HttpParams("orderString", createOrderJson()).toString());

        HttpUtils.post(Config.SUBMIT_ORDER, TAG, new HttpParams("orderString", createOrderJson()), new HttpCallBack(VerifyGoodsOrderActivity.this) {

            @Override
            public void onBefore(BaseRequest request) {
                if (loadingDialog == null || loadingDialog.isShowing()) return;
                loadingDialog.show();
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                if (loadingDialog == null) return;
                loadingDialog.dismiss();
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                OrderResult orderResult = AbJsonUtil.fromJson(result.toString(), OrderResult.class);
                Intent intent = new Intent(VerifyGoodsOrderActivity.this, CashierDeskActivity.class);
                HashMap<String, Class> map = new HashMap<>();
                map.put(CashierDeskActivity.GOTO_ACTIVITY, MyAllOrderActivity.class);
                intent.putExtra(CashierDeskActivity.GOTO_ACTIVITY, map); // 支付成功之后跳转的activity
                intent.putExtra(CashierDeskActivity.ORDER_RESULT, orderResult); // 订单总额
                intent.putExtra(CashierDeskActivity.PAYMENT_TYPE, CashierDeskActivity.ORDER_PAY); // 支付类型
                intent.putExtra(CashierDeskActivity.ORDER_TYPE, "SC"); // 订单类型
                startActivity(intent);
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(VerifyGoodsOrderActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 构造cartIds, cartId跟商品是一对一关系
     *
     * @return string
     */
    private String createCartIdsStr() {
        if (balanceAccountResult == null || balanceAccountResult.getCartGoodsList() == null)
            return null;
        StringBuilder cartIds = new StringBuilder();
        int goodsLen = balanceAccountResult.getCartGoodsList().size();
        for (int i = 0; i < goodsLen; i++) {
            CartGoodsEntity goods = balanceAccountResult.getCartGoodsList().get(i);
            if (goods == null) return null;
            cartIds.append(goods.getCartId());
            cartIds.append(";");
        }
        return cartIds.toString();
    }

    /**
     * 构造提交订单的参数
     *
     * @return json
     */
    private String createOrderJson() {
        if (balanceAccountResult == null) return "";
        List<String> cartIds = new ArrayList<>();
        int goodsLen = balanceAccountResult.getCartGoodsList().size();
        for (int i = 0; i < goodsLen; i++) {
            CartGoodsEntity goods = balanceAccountResult.getCartGoodsList().get(i);
            if (goods == null) return null;
            cartIds.add(goods.getCartId());
        }
        request.setStoreId(balanceAccountResult.getStoreId());
        request.setStoreName(balanceAccountResult.getStoreName());
        request.setCartIds(cartIds);
        request.setLeaveWord(edtMessage.getText().toString().trim());
        request.setCouponId(mCouponId);
        request.setAddressId(mAddressId);
        request.setTotalPrice(balanceAccountResult.getTotalPrice());
        request.setIsPayPoint(balanceAccountResult.getIsPayPoint());
        request.setPointBalance(balanceAccountResult.getPointBalance());

        if(mSelectTransport != null) {
            request.setTransportPrice(mSelectTransport.getTransportPrice());
            request.setTransportId(mSelectTransport.getTransportId());
            request.setTransportName(mSelectTransport.getTransportName());
        }
//        orderString=[{"addressId":"123","cartIds":["2241"],"couponId":"","leaveWord":"",
//                "storeId":"35","storeName":"幸福之家","transportId":"kd","transportName":"快递",
//                "transportPrice":"7.0"}]
//
////        "totalPrice":"415.00",   "addressId": "206",     "storeId": "35", "storeName": "幸福之家",
////                "couponId": "",         "transportId": "kd",         "transportName": "快递",
////                "transportPrice": "15.00",         "leaveWord": "卖家留言++++++++++++",
////                "isPayPoint":"0",         "pointBalance":"0",
////                "cartIds": [             "2227"         ] }
        return AbJsonUtil.toJson(request);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }
}
